package com.aimao.blog.controller;

import com.aimao.blog.bo.ArticlePushBo;
import com.aimao.blog.constant.ServerConst;
import com.aimao.blog.constant.ServerResponse;
import com.aimao.blog.pojo.*;
import com.aimao.blog.service.*;
import com.aimao.blog.service.impl.AutoClearOverdueImg;
import com.aimao.blog.util.CustomMap;
import com.aimao.blog.vo.UploadResult;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * @Author PuaChen
 * @Create 2018-07-03 21:36
 */
@RestController
@RequestMapping("/background")
public class AdminController {

    private org.slf4j.Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private AccountAdminService accountAdminService;

    @Autowired
    private ArticleAdminService articleAdminService;

    @Autowired
    private SortAdminService sortAdminService;

    @Autowired
    private TagAdminService tagAdminService;

    @Autowired
    private CommentAdminService commentAdminService;

    @Autowired
    private SubjectAdminService subjectAdminService;

    @Autowired
    private FileUploadService fileUploadService;

    @Autowired
    private AutoClearOverdueImg autoClearOverdueImg;

    ///////////////////////////////////////////////////////////////////////////
    // 修改我的个人信息的接口
    ///////////////////////////////////////////////////////////////////////////


    @PostMapping("/login")
    public ServerResponse<Admin> login(String id, String pwd, HttpSession session) {
        if (StringUtils.isBlank(id) || StringUtils.isBlank(pwd)) {
            return ServerResponse.createFailure("ERROR:参数为空");
        }
        ServerResponse<Admin> res = accountAdminService.login(id, pwd);
        if (res.isSuccess()) {
            Admin admin = res.getData();
            session.setAttribute(ServerConst.CURRENT_USER, admin);
        }
        return res;
    }

    @PostMapping("/logout")
    public ServerResponse logout(HttpSession session) {
        Admin admin = (Admin) session.getAttribute(ServerConst.CURRENT_USER);
        if (admin == null) {
            return ServerResponse.createFailure("未登录");
        }
        session.invalidate();
        return ServerResponse.createSuccess();
    }

    @PostMapping("/get-admin")
    public ServerResponse<Admin> getAdmin(HttpSession session) {
        Admin admin = (Admin) session.getAttribute(ServerConst.CURRENT_USER);
        if (admin == null) {
            return ServerResponse.createFailure("未登录");
        }
        return ServerResponse.createSuccessAndData(admin);
    }

    @PostMapping("/update-admin")
    public ServerResponse updateAdmin(String name, String head, HttpSession session) {
        Admin admin = (Admin) session.getAttribute(ServerConst.CURRENT_USER);
        ServerResponse<Admin> res = accountAdminService.updateAdmin(admin.getId(), name, head);
        if (res.isSuccess()) {
            session.setAttribute(ServerConst.CURRENT_USER, res.getData());
        }
        return res;
    }

    @PostMapping("/update-admin-pwd")
    public ServerResponse updateAdminPwd(String oldPwd, String newPwd, HttpSession session) {
        Admin admin = (Admin) session.getAttribute(ServerConst.CURRENT_USER);
        ServerResponse<Admin> res = accountAdminService.updateAdminPassword(admin.getId(), oldPwd, newPwd);
        if (res.isSuccess()) {
            session.setAttribute(ServerConst.CURRENT_USER, res.getData());
        }
        return res;
    }

    ///////////////////////////////////////////////////////////////////////////
    // 文章管理Api接口
    ///////////////////////////////////////////////////////////////////////////

    @RequestMapping("/get-article-all")
    public ServerResponse getArticleList(String key, Integer sortId, boolean isSplit, Integer page, Integer size) {
        if (StringUtils.isNotBlank(key) && sortId == null) {
            return articleAdminService.findToLike(key, isSplit, page, size);
        }
        if (sortId != null && StringUtils.isBlank(key)) {
            return articleAdminService.findAllBySortId(sortId, isSplit, page, size);
        }
        return articleAdminService.findALl(isSplit, page, size);
    }

    @PostMapping("/get-article-ids")
    public ServerResponse getArticleByIds(String ids, boolean isSplit, Integer page, Integer size) {
        List<Integer> list = null;
        ids = ids.replaceAll("\\\"", "");
        try {
            list = JSONArray.parseArray(ids, Integer.class);
        } catch (Exception e) {
            logger.error("解析JSON出错：", e);
            return ServerResponse.createFailure("传入的IDS不符合JSON规范，解析失败");
        }
        if (list == null || list.isEmpty()) {
            return ServerResponse.createFailure("IDS为空");
        }
        return articleAdminService.findToIdList(list, isSplit, page, size);
    }

    @RequestMapping("/update-article-top")
    public ServerResponse setArticleTop(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return articleAdminService.setTop(id);
    }

    @RequestMapping("/del-article")
    public ServerResponse deleteArticle(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return articleAdminService.deleteArticle(Arrays.asList(id));
    }

    @PostMapping("/update-article")
    public ServerResponse updateArticle(@RequestBody Article article) {
        if (article == null || article.getId() == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return articleAdminService.updateArticle(article);
    }


    @PostMapping("/update-article-push-draft")
    public ServerResponse updatePushDraftToNormal(@RequestBody List<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return ServerResponse.createFailure("参数错误");
        }
        return articleAdminService.pushDraftToNormal(ids);
    }

    @PostMapping("/push-article")
    public ServerResponse pushArticle(@RequestBody ArticlePushBo articlePushBo) {
        if (articlePushBo == null) {
            return ServerResponse.createFailure("参数错误");
        }

        return articleAdminService.pushArticle(articlePushBo.getArticle());
    }

    ///////////////////////////////////////////////////////////////////////////
    // 小标签API
    ///////////////////////////////////////////////////////////////////////////

    @RequestMapping("/get-tag-all")
    public ServerResponse getTagAll(String key, boolean isSplit, Integer page, Integer size) {
        if (StringUtils.isNotBlank(key)) {
            return tagAdminService.findToLike(key, isSplit, page, size);
        }
        return tagAdminService.findAll(isSplit, page, size);
    }

    @RequestMapping("/update-tag")
    public ServerResponse updateTag(Integer id, String name) {
        if (id == null || StringUtils.isBlank(name)) {
            return ServerResponse.createFailure("参数错误");
        }
        return tagAdminService.updateTag(id, name);
    }

    @RequestMapping("/del-tag")
    public ServerResponse deleteTag(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return tagAdminService.deleteTag(id);
    }

    @RequestMapping("/add-tag")
    public ServerResponse addTag(String name) {
        if (StringUtils.isNotBlank(name)) {
            Tag tag = new Tag();
            tag.setName(name);
            return tagAdminService.addTag(tag);
        }
        return ServerResponse.createFailure("参数错误");
    }

    ///////////////////////////////////////////////////////////////////////////
    // 主分类API
    ///////////////////////////////////////////////////////////////////////////

    @RequestMapping("/get-sort-all")
    public ServerResponse getSortAll(String key, boolean isSplit, Integer page, Integer size) {
        if (StringUtils.isNotBlank(key)) {
            return sortAdminService.findToLike(key, isSplit, page, size);
        }
        return sortAdminService.findAll(isSplit, page, size);
    }

    @RequestMapping("/update-sort")
    public ServerResponse updateSort(Integer id, String name) {
        if (id == null || StringUtils.isBlank(name)) {
            return ServerResponse.createFailure("参数错误");
        }
        return sortAdminService.updateSort(id, name);
    }

    @RequestMapping("/del-sort")
    public ServerResponse deleteSort(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return sortAdminService.deleteSort(id);
    }

    @RequestMapping("/add-sort")
    public ServerResponse addSort(String name) {
        if (StringUtils.isNotBlank(name)) {
            Sort sort = new Sort();
            sort.setName(name);
            return sortAdminService.addSort(sort);
        }
        return ServerResponse.createFailure("参数错误");
    }

    ///////////////////////////////////////////////////////////////////////////
    // 草稿箱API
    ///////////////////////////////////////////////////////////////////////////

    @RequestMapping("/get-draft-all")
    public ServerResponse getDraftAll(boolean isSplit, Integer page, Integer size) {
        return articleAdminService.findDraftToAll(isSplit, page, size);
    }

    @PostMapping("/del-draft-list")
    public ServerResponse deleteDraftAsList(@RequestBody ArrayList<Integer> ids) {
        if (ids == null || ids.isEmpty()) {
            return ServerResponse.createFailure("参数错误");
        }
        return articleAdminService.deleteArticle(ids);
    }


    ///////////////////////////////////////////////////////////////////////////
    // 评论管理
    ///////////////////////////////////////////////////////////////////////////

    @RequestMapping("/get-comment-new")
    public ServerResponse getCommentNewList(Integer size) {
        if (size == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return commentAdminService.findNewCommentList(size);
    }

    @RequestMapping("/get-comment-key")
    public ServerResponse getCommentByTitleKey(String key) {
        if (StringUtils.isBlank(key)) {
            return ServerResponse.createFailure("参数错误");
        }
        return commentAdminService.findCommentByKeyWord(key);
    }

    @RequestMapping("/get-comment-detail")
    public ServerResponse getCommentDetail(Integer id, boolean isSplit, Integer page, Integer size) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return commentAdminService.findAll(id, isSplit, page, size);
    }

    @RequestMapping("/del-comment")
    public ServerResponse deleteCommentById(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return commentAdminService.deleteComment(id);
    }

    @PostMapping("/update-comment")
    public ServerResponse updateCommentById(Integer id, String content) {
        if (id == null || StringUtils.isBlank(content)) {
            return ServerResponse.createFailure("参数错误");
        }
        return commentAdminService.updateComment(id, content);
    }

    @PostMapping("/reply-comment")
    public ServerResponse replyComment(Integer parentId, Integer articleId, String content) {
        if (parentId == null || StringUtils.isBlank(content) || articleId == null) {
            return ServerResponse.createFailure("参数错误");
        }
        Comment comment = new Comment();
        comment.setContent(content);
        comment.setArticleid(articleId);
        comment.setStatus(true);
        comment.setUsername("站长回复");
        comment.setReadstate(true);
        return commentAdminService.replyComment(parentId, comment);
    }


    ///////////////////////////////////////////////////////////////////////////
    // 主题管理API接口
    ///////////////////////////////////////////////////////////////////////////

    @PostMapping("/add-subject")
    public ServerResponse createSubject(@RequestBody Subject subject) {
        if (subject == null) {
            return ServerResponse.createFailure("参数错误");
        }
        try {
            parseComputeCount(subject);
        } catch (InterruptedException e) {
            return ServerResponse.createFailure("JSON格式有误");
        }
        return subjectAdminService.addSubject(subject);
    }

    /**
     * 计算出文章总数
     *
     * @param subject
     * @throws InterruptedException
     */
    private void parseComputeCount(Subject subject) throws InterruptedException {
        try {
            List<Integer> list = JSONArray.parseArray(subject.getArticlelist().replaceAll("\\\"", ""), Integer.class);
            subject.setArticlecount(Long.valueOf(list.size()));
        } catch (Exception e) {
            logger.error("转换JSOn失败", e);
            throw new InterruptedException("转换JSOn失败");
        }
    }

    @RequestMapping("/get-subject")
    public ServerResponse getSubject(boolean isSplit, Integer page, Integer size) {
        return subjectAdminService.findAll(isSplit, page, size);
    }

    @RequestMapping("/get-subject-id")
    public ServerResponse getSubjectById(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return subjectAdminService.findById(id);
    }

    @RequestMapping("/del-subject")
    public ServerResponse deleteSubject(Integer id) {
        if (id == null) {
            return ServerResponse.createFailure("参数错误");
        }
        return subjectAdminService.deleteSubject(id);
    }

    @PostMapping("/update-subject")
    public ServerResponse updateSubject(@RequestBody Subject subject) {
        if (subject == null) {
            return ServerResponse.createFailure("参数错误");
        }
        if (StringUtils.isNotBlank(subject.getArticlelist())) {
            try {
                parseComputeCount(subject);
            } catch (InterruptedException e) {
                return ServerResponse.createFailure("JSON格式有误");
            }
        }
        return subjectAdminService.updateSubject(subject);
    }

    ///////////////////////////////////////////////////////////////////////////
    // 文件上传的API
    ///////////////////////////////////////////////////////////////////////////

    @PostMapping("/upload")
    public ServerResponse upload(MultipartFile file, String prefix) {
        if (file == null || file.isEmpty()) {
            return ServerResponse.createFailure("文件为空");
        }
        return fileUploadService.upload(file, null, prefix);
    }

    @PostMapping("/upload-ueditor")
    public Map<String, Object> uploadForUeditor(MultipartFile[] file) {
        Map<String, Object> map = new HashMap<>(4);
        if (file != null && file.length != 0) {
            for (MultipartFile item : file) {
                ServerResponse<UploadResult> response = fileUploadService.upload(item, null, "article-");
                if (response.isSuccess()) {
                    //成功的
                    map.put("original", response.getData().getOriginalName());
                    map.put("name", response.getData().getNewName());
                    map.put("url", response.getData().getAbsoluteUrl());
                    map.put("state", "SUCCESS");
                } else {
                    //失败的
                    map.put("original", "");
                    map.put("name", "");
                    map.put("url", "");
                    map.put("state", response.getMsg());
                }
            }
        } else {
            //失败的
            map.put("original", "");
            map.put("name", "");
            map.put("url", "");
            map.put("state", "参数为不正确");
        }
        return map;
    }

    ///////////////////////////////////////////////////////////////////////////
    // 主页
    ///////////////////////////////////////////////////////////////////////////

    /**
     * 获取主页统计的数据
     *
     * @return
     */
    @RequestMapping("/getStatisticsData")
    public ServerResponse<Map<String, Object>> getStatisticsData() {
        return accountAdminService.getStatisticsData();
    }

    @RequestMapping("/updateCommentDown")
    public ServerResponse updateCommentDown(@RequestBody List<Integer> ids) {
        if (ids == null || ids.size() == 0) {
            return ServerResponse.createFailure("参数为空");
        }
        return accountAdminService.setCommentStatus(ids);
    }

    @RequestMapping("/article-cancel-all-top")
    public ServerResponse cancelTopAll() {
        return articleAdminService.updateCancelTopAll();
    }


    /**
     * 自动删除所有的用不到的文件
     *
     * @return
     */
    @PostMapping("/auto-delete-file")
    public ServerResponse autoDelOverdueFile() {
        AutoClearOverdueImg autoClearOverdueImg = this.autoClearOverdueImg;
        boolean state = autoClearOverdueImg.autoDelete();
        return state ? ServerResponse.createSuccess() : ServerResponse.createFailure();
    }

    /**
     * 返回系统状态
     *
     * @return
     */
    @RequestMapping("/auto-system-status")
    public ServerResponse getDataBaseImgCount() {
        ServerResponse<CustomMap> res = ServerResponse.createSuccessAndData(CustomMap.create()
                .add("databaseSize", autoClearOverdueImg.getImgFileSize())
                .add("dirSize", autoClearOverdueImg.getImgFileSizeByDir()));
        res.getData().putAll(autoClearOverdueImg.getDirConfig());
        return res;
    }

    /**
     * 清空缓存的所有数据
     *
     * @return
     */
    @PostMapping("/auto-system-clearCache")
    public ServerResponse clearCacheForRedis() {
        autoClearOverdueImg.clearChache();
        logger.info("----清空Redis所有的缓存数据");
        return ServerResponse.createSuccess();
    }

}
